import { UserService } from './../services/management-service/user.service';
import { StorageService } from './storage.service';
import app from '~/config/app.config'
import store from '~/store'
import Stomp from '@stomp/stompjs'
import { Observable } from "rxjs";
import SockJS from 'sockjs-client'
import { format as DateFormat } from 'date-fns';

/**
 * 支持的消息类型
 */
export enum ReminderMessageType {
  /**
   * 普通消息 Reminder
   */
  Reminder = "REMINDER_MESSAGE",
  /**
   * 任务消息 TASK_BOX
   */
  Task = "TASK_BOX",
  /**
   * 后台私有消息
   */
  Background = "BACKGROUND"
}

export class ReminderService {

  /**
   * 打开消息服务
   */
  public static connect() {
    if (!this.mIinstance) {
      this.getInstance()
    }
    return this.mIinstance.client;
  }

  /**
   * 关闭消息服务
   */
  public static disConnect() {
    if (!this.mIinstance) return
    if (this.mIinstance.client) {
      this.mIinstance.client.disconnect()
    }
  }

  /**
   * 获取 ReminderService 对象实例
   */
  public static getInstance() {
    if (!this.mIinstance) {
      this.mIinstance = new ReminderService()
    }
    return this.mIinstance
  }

  // 静态私有实例
  private static mIinstance: ReminderService
  // 监听列表
  private static listenerList: Array<{ type: ReminderMessageType, observer: any, backgroundType?: string }> = []
  // private static notifyList: any[] = []
  // stomp 客户端
  private client: Stomp.Client

  /**
   * 初始化65
   */
  private constructor() {
    const userData: any = StorageService.getItem('vuex').userData

    // if (app.rabbitmq.socket.startsWith('ws://') || app.rabbitmq.socket.startsWith('wss://')) {
    //   // websocket路径 
    //   this.client = Stomp.client(app.rabbitmq.socket + `?username=` + encodeURIComponent(userData.id));
    // } else {
      // http/https路径
      // const ws = new SockJS(app.rabbitmq.socket + `?username=` + encodeURIComponent(userData.id));
      // this.client = Stomp.over(ws);
    // }

    // if (!app.debug) {
    //   console.log("非Debug模式,已关闭reminder日志")
    // }
    // this.client.debug = () => { };  // 生产模式禁用日志消息
    // this.client.connect(
    //   userData.id,
    //   '',
    //   this.onConnectHandle.bind(this),
    //   this.onErrorHandle.bind(this),
    //   this.onCloseHandle.bind(this),
    //   '');

  }

  /**
   * 添加消息监听
   * @param type 
   * @param backgroundType 后台消息体,业务类型
   */
  public addListener(type: ReminderMessageType, backgroundType?: string) {
    if (backgroundType) {
      // 如果有单独消息监听者
      const index = ReminderService.listenerList.
        findIndex(x => x.type === type && x.backgroundType === backgroundType)
      // 删除之前监听列表存在的
      if (index > -1) {
        ReminderService.listenerList.splice(index, 1)
      }
    }

    // 添加监听方式
    return Observable.create(observer => {
      ReminderService.listenerList.push({ type, observer, backgroundType })
    })

  }

  /**
   * 处理消息open事件
   */
  private onConnectHandle() {
    console.log("reminder connected !", DateFormat(Date.now(), "YYYY-MM-DD HH:mm:ss"))
    // this.client.subscribe(`${app.rabbitmq.exchange}/${store.state.userData.id}`, this.onReminderHandle.bind(this));
    this.client.subscribe(
      "/user/topic/private",
      this.onReminderHandle.bind(this)
    );
  }

  /**
   * 处理消息message事件
   */
  private onReminderHandle({ body }) {
    try {
      // messageType 与后端定义好的消息体区分
      const { messageType, data } = JSON.parse(body)
      if (app.debug) {
        console.log({ messageType, data }, "ReminderMessage")
      }
      // 后台消息
      if (messageType === ReminderMessageType.Background) {
        // 查找单独订阅此消息内容体的订阅者
        const listener = ReminderService.listenerList.find(x => {
          return x.type === ReminderMessageType.Background
            && x.backgroundType === data.backgroundType
        })
        if (listener) {
          listener.observer.next(data)
        }
      } else {
        // 前台所有消息都需要广播
        const receiveList = ReminderService.listenerList.filter(x => x.type === messageType)
        receiveList.forEach(x => x.observer.next(data))
      }
    } catch (ex) {
      console.log(ex.message)
    }
  }

  /**
   * 处理消息close事件
   */
  private onCloseHandle(...a) {
    console.log('close', a)
  }

  /**
   * 处理消息error事件
   */
  private onErrorHandle(...a) {
    console.log('error', a)
  }
}
